'use strict'

const { ApiController } = require('jax')
const helper = require('jax/app/utils/helper')

class Controller extends ApiController {
  // 模型
  get Model() {
    return this.ctx.model.UserActivity
  }

  // 匹配查询
  get searchKey() {
    return ['storeId', 'verifyStatus']
  }

  // 模糊查询
  get likeKey() {
    return []
  }

  // 返回JSON字段
  get json() {
    return [
      'id',

      // 添加的
      'name',
      'mobile',
      'sex',
      'role',

      'goods',
      // 'goodsName',
      // 'goodsNum',
      // 'channel',
      // 'goodsImages',

      'startTime',
      'endTime',
      'activityDate',
      'activityNo',
      'storeName',
      'remark',

      'verifyStatus',
      'verifyResult',
    ]
  }

  // 查询前
  async beforeIndex() {
    const { ctx } = this
    const { ACTIVITY_STATUS_CANCEL, ACTIVITY_STATUS_AUDIT_WAIT, ACTIVITY_STATUS_AUDIT_REFUSE } =
      this.config.constant
    const { query } = ctx

    const filter = {
      status: {
        $nin: [ACTIVITY_STATUS_CANCEL, ACTIVITY_STATUS_AUDIT_WAIT, ACTIVITY_STATUS_AUDIT_REFUSE],
      },
    }

    // 关键字模糊查询
    if (query.keyword && !query.keyword == '') {
      const reg = new RegExp(helper.toMongoRegex(query.keyword, 'i'))
      filter.$or = [{ name: reg }, { mobile: reg }]
    }

    return {
      filter,
    }
  }

  // 详情查询前
  async beforeShow(filter) {
    const { ctx } = this
    const { ACTIVITY_STATUS_CANCEL, ACTIVITY_STATUS_AUDIT_WAIT, ACTIVITY_STATUS_AUDIT_REFUSE } =
      this.config.constant

    filter.status = {
      $nin: [ACTIVITY_STATUS_CANCEL, ACTIVITY_STATUS_AUDIT_WAIT, ACTIVITY_STATUS_AUDIT_REFUSE],
    }
  }

  // 修改
  async update() {
    const { ctx } = this
    const { helper } = ctx
    const { body } = ctx.request
    const { ACTIVITY_STATUS_VERIFY_WAIT } = this.config.constant

    const id = this.ctx.params.id

    const userActivity = await ctx.model.UserActivity.findById(id)

    if (!userActivity) throw '获取预约信息失败'
    if (userActivity.status != ACTIVITY_STATUS_VERIFY_WAIT) throw new Error('当前状态不允许修改')

    const keys = [
      'name',
      'mobile',
      'sex',
      'role',
      'goods',
      // 'goodsName', 'goodsNum', 'channel', 'goodsImages'
    ]
    const newData = helper.validate(body, {
      required: keys,
      include: [...keys, 'remark'],
    })

    await ctx.model.UserActivity.updateOne({ _id: userActivity.id }, newData)

    ctx.body = {
      code: 0,
      msg: 'success',
    }
  }

  // 核销
  async verify() {
    const { ctx } = this
    const { ACTIVITY_STATUS_VERIFY_WAIT, ACTIVITY_STATUS_VERIFY_SUCCESS } = this.config.constant
    const { helper } = ctx
    const { body } = ctx.request

    const keys = ['verifyId']
    const newData = helper.validate(body, {
      required: keys,
      include: [...keys, 'remark'],
    })

    const userActivity = await ctx.model.UserActivity.findById(body.verifyId)

    if (!userActivity) throw '核销记录不存在'
    if (userActivity.status != ACTIVITY_STATUS_VERIFY_WAIT) throw '无法核销'

    // await ctx.model.UserActivity.updateOne({ _id: userActivity.id }, newData)

    delete body.verifyId

    const verifyUser = await ctx.model.User.findById(ctx.state.user.id)
    if (!verifyUser) throw '核销人员信息获取失败'

    userActivity.status = ACTIVITY_STATUS_VERIFY_SUCCESS // 2：已核销
    userActivity.verifyStatus = 1 // 1：已核销
    userActivity.verifyResult = body
    userActivity.verifyUserId = verifyUser.id
    userActivity.verifyUserName = verifyUser.name || verifyUser?.nickname
    userActivity.verifyTime = new Date()

    await userActivity.save()

    // 成为门店用户
    await ctx.model.StoreUser.updateOne(
      {
        userId: userActivity.userId,
        storeId: userActivity.storeId,
      },
      {},
      {
        upsert: true, // 不存在插入
        setDefaultsOnInsert: true, // 允许插入默认值
      }
    )

    ctx.body = {
      code: 0,
      msg: 'success',
    }
  }

  // 统计
  async stat() {
    const { ctx } = this
    const {
      ACTIVITY_STATUS_CANCEL,
      ACTIVITY_STATUS_AUDIT_WAIT,
      ACTIVITY_STATUS_AUDIT_REFUSE,
      ACTIVITY_STATUS_VERIFY_WAIT,

      ACTIVITY_STATUS_SUCCESS,
      ACTIVITY_STATUS_VERIFY_SUCCESS,
    } = this.config.constant
    const { query } = ctx

    const filter = {
      status: {
        $ne: [
          ACTIVITY_STATUS_CANCEL,
          ACTIVITY_STATUS_AUDIT_WAIT,
          ACTIVITY_STATUS_AUDIT_REFUSE,

          ACTIVITY_STATUS_SUCCESS,
          ACTIVITY_STATUS_VERIFY_SUCCESS,
        ],
      },
    }

    if (query.storeId) filter.storeId = query.storeId

    // 关键字模糊查询
    if (query.keyword && !query.keyword == '') {
      const reg = new RegExp(helper.toMongoRegex(query.keyword, 'i'))
      filter.$or = [{ name: reg }, { mobile: reg }]
    }

    const returnData = {}

    await Promise.all([
      // 待核销
      ctx.model.UserActivity.count({
        ...filter,
        status: ACTIVITY_STATUS_VERIFY_WAIT,
      }).then((count) => {
        returnData.pending = count
      }),
      // 已核销
      ctx.model.UserActivity.count({
        ...filter,
        status: {
          $in: [ACTIVITY_STATUS_VERIFY_SUCCESS, ACTIVITY_STATUS_SUCCESS],
        },
      }).then((count) => {
        returnData.completed = count
      }),
    ])

    // 全部
    returnData.all = returnData.pending + returnData.completed

    ctx.body = {
      code: 0,
      msg: 'success',
      data: returnData,
    }
  }
}

module.exports = Controller
